package com.vic.hutool.growth;

import lombok.extern.slf4j.Slf4j;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @author victor
 */
@Slf4j
public class GrowthUtils {

    /*** 签名⽅法
     * @param data 原始数据
     * @param privateKeyStr 私钥
     * @return *
     * @throws Exception
     */
    public static String getSign(String data, String privateKeyStr) {
        try {
            PrivateKey privateKey = getPrivateKeyByStr(privateKeyStr);
            Signature signature = Signature.getInstance("Sha1WithRSA");
            signature.initSign(privateKey);
            signature.update(data.getBytes("UTF-8"));
            byte[] signed = signature.sign();
            return new String(Base64.getEncoder().encode(signed));
        } catch (Exception e) {
            log.error("Growth 获取签名异常：", e);
        }
        return "";
    }

    /**
     * 私钥字符串->⽣成私钥对象
     * @param privateKeyStr
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static PrivateKey getPrivateKeyByStr(String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //1、获取私钥数据
        byte[] bytesPrivateBase64 = privateKeyStr.getBytes();
        // 2、对读取回来的数据进⾏Base64解码
        byte[] bytesPrivate = Base64.getDecoder().decode(bytesPrivateBase64);
        //3、把解码后的数据,重新封装成⼀个PrivateKey对象
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytesPrivate);
        KeyFactory keyFactory = null;
        keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
}
